package com.util;

import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.afterturn.easypoi.handler.inter.IReadHandler;
import cn.hutool.core.io.FileUtil;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.util.LinkedList;
import java.util.List;

/**
 * excel相关工具类
 *
 * @author heyonghao
 * @date 2023/1/19
 */
public class ExcelHandlerUtil {


    /**
     * excel导入
     * @param file 上传文件
     * @param c    导入数据对象class
     * @param <T>  导入泛型
     * @return List
     */
    public static <T> List<T> importExcel(MultipartFile file,Class<T> c){
        List<T> res = new LinkedList<>();
        String originalFilename = file.getOriginalFilename();
        //文件后缀名
        String suffix = FileUtil.getSuffix(originalFilename);
        //导入配置
        ImportParams params = new ImportParams();
        try {
            InputStream in = file.getInputStream();
            ExcelImportUtil.importExcelBySax(in, c, params, new IReadHandler<T>() {
                @Override
                public void handler(T t) {
                    res.add(t);
                }
                @Override
                public void doAfterAll() {
                    System.out.println("数据导入结束");
                }
            });
        } catch (IOException e) {
            e.printStackTrace();
        }
        return res;
    }

    /**
     * excel 浏览器文件下载
     * @param fileName
     * @param response
     * @param workbook
     */
    public static void downLoadExcel(String fileName, HttpServletResponse response, Workbook workbook) {
        try {
            response.reset();
            response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
            response.setContentType("application/octet-stream");
            ServletOutputStream outputStream = response.getOutputStream();
            workbook.write(outputStream);
            outputStream.flush();
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            try {
                workbook.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }


    /**
     * 获取模板文件路径 template.xlsx
     * @return File
     */
    public static String getTemplateFile(String templateName) {
        File file = new File("");
        return  file.getAbsolutePath() + File.separator + "template" + File.separator + templateName + ".xlsx";
    }

}
